package com.vancouver.knows.ui.activity.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;

import com.pangu.task.mark.ATaskMark;
import com.pangu.ui.adapter.AGroupItemAdapter;
import com.pangu.ui.adapter.IGroupPinnedAdapter;
import com.pangu.ui.browser.PinnedGroupItemBroswer;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.ui.activity.citydiscount.CityDiscountDetailActivity;
import com.vancouver.knows.ui.activity.citynews.CityNewsDetailActivity;
import com.vancouver.knows.ui.activity.event.EventDetailActivity;
import com.vancouver.knows.util.PhoConstants;
import com.vancouver.knows.business.BusinessModule;
import com.vancouver.knows.business.bean.SearchPostInfo;
import com.vancouver.knows.business.service.impl.SearchInfoHandle;

public class SearchListView extends PinnedGroupItemBroswer<MainApplication> {

	private Context mContext;
	private BusinessModule bModule;
	private int mTotalCountPost;
	private int mTotalCountEvent;
	private int mTotalCountBusiness;
	private String keyWork;
	private String fromType;

	private String KEY_POSTS = "post_result";
	private String KEY_EVENT_RESULT = "event_result";
	private String KEY_BUSINESS_RESULT = "business_result";

	private final String all = "ALL";
	private final String post = "post";
	private final String event = "event";
	private final String business = "business";
	private String sendType = all;

	public SearchListView(Context context) {
		super(context);
		mContext = context;
		init();
	}

	private void init() {
		bModule = imContext.getBusinessModule();
	}

	@Override
	protected BaseAdapter createAdapter() {
		return new searchAdapter();
	}

	public void initLoadableView(String keyWork, ATaskMark taskWraper, String fromType) {
		this.keyWork = keyWork;
		this.fromType = fromType;
		super.initLoadableView(taskWraper);
	}

	@Override
	protected void handleLoadNewItems(ATaskMark taskMark) {
		// 发送登录需要的参数
		if (PhoConstants.FROM_CITY_NEWS.equals(fromType)) {
			sendType = post;
			bModule.getServiceWrapper().userSearch(this, taskMark, keyWork, post, "0", "5", null);
		} else if (PhoConstants.FROM_EVENTS.equals(fromType)) {
			sendType = event;
			bModule.getServiceWrapper().userSearch(this, taskMark, keyWork, event, "0", "5", null);
		} else if (PhoConstants.FROM_CITY_DISCOUNT.equals(fromType)) {
			sendType = business;
			bModule.getServiceWrapper().userSearch(this, taskMark, keyWork, business, "0", "5", null);
		} else {
			sendType = all;
			bModule.getServiceWrapper().userSearch(this, taskMark, keyWork, null, null, null, null);
		}
	}

	@Override
	protected void setListViewParameter(ExpandableListView listView) {
		super.setListViewParameter(listView);
		ColorDrawable drawable = new ColorDrawable(getResources().getColor(R.color.line_color));
		listView.setDivider(drawable);
		listView.setDividerHeight(1);
		listView.setChildDivider(drawable);
	}

	public class searchAdapter extends AGroupItemAdapter<SearchPostInfo> implements IGroupPinnedAdapter {

		private LayoutInflater inflater;

		public searchAdapter() {
			inflater = LayoutInflater.from(getContext());
		}

		@Override
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.search_group_item, parent, false);
				GroupViewHolder viewHolder = new GroupViewHolder(convertView);
				convertView.setTag(viewHolder);
			}

			String groupName = (String) getGroup(groupPosition);
			GroupViewHolder viewHolder = (GroupViewHolder) convertView.getTag();
			viewHolder.groupTitle.setText(Html.fromHtml(groupName));

			if (!((ExpandableListView) getAdapterView()).isGroupExpanded(groupPosition)) {
				((ExpandableListView) getAdapterView()).expandGroup(groupPosition);

			}

			return convertView;
		}

		public class GroupViewHolder {

			@Bind(R.id.groupTitle)
			TextView groupTitle;

			public GroupViewHolder(View view) {
				ButterKnife.bind(this, view);
			}

		}

		@Override
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				convertView = createItemView(parent);
			}

			SearchPostInfo postResultInfo = (SearchPostInfo) getChild(groupPosition, childPosition);
			if (postResultInfo != null) {
				initPostItemView(convertView, postResultInfo, groupPosition, childPosition);
			}

			return convertView;
		}

		private View createItemView(ViewGroup parent) {
			View view = inflater.inflate(R.layout.search_item, parent, false);
			ChildViewHolder viewHolder = new ChildViewHolder(view);
			view.setTag(viewHolder);

			return view;
		}

		private void initPostItemView(View convertView, final SearchPostInfo postResultInfo, final int groupPosition,
				final int childPosition) {
			ChildViewHolder viewHolder = (ChildViewHolder) convertView.getTag();
			String titleCon = postResultInfo.getPostTitle();
			String titleType = postResultInfo.getTitleType();
			if (titleCon.equals(KEY_POSTS) || titleCon.equals(KEY_EVENT_RESULT) || titleCon.equals(KEY_BUSINESS_RESULT)) {
				if (titleType.equals(KEY_POSTS)) {
					titleCon = mContext.getString(R.string.search_chk_all, mTotalCountPost);
				} else if (titleType.equals(KEY_EVENT_RESULT)) {
					titleCon = mContext.getString(R.string.search_chk_all, mTotalCountEvent);
				} else if (titleType.equals(KEY_BUSINESS_RESULT)) {
					titleCon = mContext.getString(R.string.search_chk_all, mTotalCountBusiness);
				}
			}
			
			titleCon = getKeyWordColor(titleCon);
			if (titleCon != null)
				viewHolder.title.setText(Html.fromHtml(titleCon));

			convertView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (sendType.equals(all)) {
						if (groupPosition == 0) {
							jumpNewDetailActivity(postResultInfo);
						} else if (groupPosition == 1) {
							jumpNewEventActivity(postResultInfo);
						} else if (groupPosition == 2) {
							jumpNewBusinessActivity(postResultInfo);
						}
					} else if (sendType.equals(post)) {
						jumpNewDetailActivity(postResultInfo);
					} else if (sendType.equals(event)) {
						jumpNewEventActivity(postResultInfo);
					} else if (sendType.equals(business)) {
						jumpNewBusinessActivity(postResultInfo);
					}
				}
			});
		}
		
		private String getKeyWordColor(String title) {
			
			if (title != null) {
				if (title.contains(keyWork)) {
					String preStr = null;
					String backStr = null;
					String middlerStr = null;
					int begin = title.indexOf(keyWork);
					if (begin != -1) {
						preStr = title.substring(0, begin);
						middlerStr = title.substring(begin , begin + keyWork.length());
						backStr = title.substring(begin + keyWork.length(), title.length());
						return preStr + "<font color=\"#ff0000\">" + middlerStr + "</font>" + backStr;
					}
				}else {
					return title;
				}
			}
			
			return title;
		}

		private void jumpNewDetailActivity(SearchPostInfo postResultInfo) {
			// 点击了城事中的查看全部栏
			if (postResultInfo.getId().equals("1")) {
				openSearchResultView(mTotalCountPost, "post");
			} else {
				Intent intent = new Intent(getContext(), CityNewsDetailActivity.class);
				intent.putExtra("postId", postResultInfo.getId());
				mContext.startActivity(intent);
			}
		}

		private void jumpNewEventActivity(SearchPostInfo postResultInfo) {
			// 点击了活动中的查看全部栏
			if (postResultInfo.getId().equals("2")) {
				openSearchResultView(mTotalCountEvent, "event");
			} else {
				Intent intent = new Intent(getContext(), EventDetailActivity.class);
				intent.putExtra("postId", postResultInfo.getId());
				mContext.startActivity(intent);
			}
		}

		private void jumpNewBusinessActivity(SearchPostInfo postResultInfo) {
			// 点击了诚惠中的查看全部栏
			if (postResultInfo.getId().equals("3")) {
				openSearchResultView(mTotalCountBusiness, "business");
			} else {
				Intent intent = new Intent(getContext(), CityDiscountDetailActivity.class);
				intent.putExtra("postId", postResultInfo.getId());
				mContext.startActivity(intent);
			}
		}

		private void openSearchResultView(int totalCount, String type) {
			Intent intent = new Intent(mContext, SearchResultActivity.class);
			intent.putExtra("TOTAL_SEARCH_RESULT", totalCount + "");
			intent.putExtra("SEARCH_KEYWORD",
					(String) bModule.getCacheManager().getSearchKeyWorkInfoMap().get("keywork"));
			intent.putExtra("SEARCH_TYPE", type);
			mContext.startActivity(intent);
		}

		public class ChildViewHolder {

			@Bind(R.id.title)
			TextView title;

			public ChildViewHolder(View view) {
				ButterKnife.bind(this, view);
			}

		}

		private String getSearchTitleName(String tabName, String keyWord) {
			return "<font color=\"#ff0000\">" + tabName + "</font>" + mContext.getString(R.string.other_plate)
					+ "<font color=\"#ff0000\">" + keyWord + "</font>" + mContext.getString(R.string.relate_contect);
		}

		@SuppressWarnings({ "unchecked", "rawtypes" })
		@Override
		protected List getItemList() {
			HashMap<String, Object> map = (HashMap<String, Object>) bModule.getCacheManager().getSearchKeyWorkInfoMap();
			if (map == null) {
				return new ArrayList<SearchPostInfo>();
			}

			List<SearchPostInfo> datas = (List<SearchPostInfo>) map.get(SearchInfoHandle.SEARCH_MAP);
			if (datas == null) {
				datas = new ArrayList<SearchPostInfo>();
			}

			return datas;
		}

		@Override
		protected String getItemGroupName(int position) {
			HashMap<String, Object> map = (HashMap<String, Object>) bModule.getCacheManager().getSearchKeyWorkInfoMap();

			int postResultSize = (Integer) map.get(SearchInfoHandle.SEARCH_POST_RESULT_COUNT);
			int postEventtSize = (Integer) map.get(SearchInfoHandle.SEARCH_EVENT_RESULT_COUNT);
			int postBusinessSize = (Integer) map.get(SearchInfoHandle.SEARCH_BUSINESS_RESULT_COUNT);

			mTotalCountPost = (Integer) map.get(SearchInfoHandle.SEARCH_TOTALCOUNT_POST);
			mTotalCountEvent = (Integer) map.get(SearchInfoHandle.SEARCH_TOTALCOUNT_EVENT);
			mTotalCountBusiness = (Integer) map.get(SearchInfoHandle.SEARCH_TOTALCOUNT_BUSINESS);

			String keyWork = (String) map.get("keywork");

			if (position < postResultSize) {
				return getSearchTitleName(mContext.getString(R.string.city_news_tab), keyWork);
			} else if (position >= postResultSize && position < (postResultSize + postEventtSize)) {
				return getSearchTitleName(mContext.getString(R.string.event_tab), keyWork);
			} else if (position >= (postResultSize + postEventtSize)
					&& position < (postResultSize + postEventtSize + postBusinessSize)) {
				return getSearchTitleName(mContext.getString(R.string.city_discount_tab), keyWork);
			} else {
				return "";
			}

		}

		@Override
		public View getPinnedHeadView() {
			View view = inflater.inflate(R.layout.search_group_item, null);
			GroupViewHolder viewHolder = new GroupViewHolder(view);
			view.setTag(viewHolder);

			return view;
		}

		@Override
		public void refreshPinnedView(View pinnedView, int firstVisibleGroupPos) {
			GroupViewHolder viewHolder = (GroupViewHolder) pinnedView.getTag();
			viewHolder.groupTitle.setText(Html.fromHtml((String) getGroup(firstVisibleGroupPos)));
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

	}

	@Override
	protected StatusView createStatusView(Context context) {
		return null;
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		return false;
	}

}
